import ColorUISdk from '../../mp-sdk/index'
import { ModelLoader } from '../../utils/3d-loader'

// 定义AR标记类型
interface ARMarker {
  id: string;
  name: string;
  desc: string;
  modelUrl: string;
  audioUrls: {
    mandarin: string;
    hakka: string;
  }
}

const sdk = new ColorUISdk({
  env: 'dev',
  version: '1.0.0',
  api: {
  dev: { 
      url: 'http://192.168.134.31:5000'
    }
  }
})

Page({
  data: {
    buildingId: '',
    buildingType: '',
    buildingName: '',
    buildingInfo: {
      name: '',
      description: '',
      audioUrl: '',
      dialectAudioUrl: ''
    },
    isPlaying: false,
    audioContext: null as any,
    audioVersion: 'mandarin',
    arMarker: null as ARMarker | null,
    isARReady: false,
    fullscreen: false,
    loading: false,
    errorMsg: '',
    cameraActive: false,
    cameraPosition: 'back',
    modelVisible: false,
    modelScale: 1.0,
    modelRotation: 0,
    modelPath: '', // 模型路径存储
    canvas: null as any,
    gl: null as any,
    canvasQueryInProgress: false,
    canvasReady: false,
    canvasQueryStatus: '未开始', // 未开始, 进行中, 成功, 失败
    modelLoaderReady: false // 新增：标记ModelLoader是否准备就绪
  },

  modelLoader: null as ModelLoader | null,

  onLoad(options: any) {
    // 从URL参数获取建筑信息
    const { buildingId, buildingType, buildingName } = options;
    
    // 从本地存储获取备份信息
    const lastBuildingInfo = wx.getStorageSync('lastBuildingInfo') || {};
    
    // 处理建筑名称
    const currentBuildingName = buildingName 
      ? decodeURIComponent(buildingName) 
      : lastBuildingInfo.name || '';
      
    // 处理建筑类型
    let currentBuildingType = buildingType || lastBuildingInfo.type || '';
    if (!currentBuildingType && currentBuildingName) {
      currentBuildingType = this.mapBuildingNameToType(currentBuildingName);
    }
    
    // 处理建筑ID
    const currentBuildingId = buildingId || lastBuildingInfo.id || '';
    
    // 设置数据
    this.setData({
      buildingId: currentBuildingId,
      buildingType: currentBuildingType,
      buildingName: currentBuildingName,
      buildingInfo: {
        ...this.data.buildingInfo,
        name: currentBuildingName
      }
    });
  },

  onReady() {
    // 检查建筑类型并加载AR内容
    const { buildingType } = this.data;
    if (buildingType) {
      this.checkBuildingTypeAndLoadAR(buildingType);
    }
    
    // 延迟检查canvas，给DOM渲染留出时间
    setTimeout(() => {
      this.checkCanvasElementExists().then(exists => {
        if (!exists) {
          console.warn('页面初始化时未检测到#arCanvas元素，请检查页面模板');
          this.setData({
            errorMsg: 'AR功能初始化失败：缺少必要的画布元素'
          });
        } else {
          this.setData({ canvasReady: true });
        }
      });
    }, 500);
  },

  // 初始化canvas和WebGL上下文
  initCanvasAndGL(): Promise<void> {
    return new Promise((resolve, reject) => {
      if (this.data.canvasQueryInProgress) {
        reject(new Error('Canvas查询已在进行中'));
        return;
      }
      
      this.setData({ 
        canvasQueryInProgress: true,
        canvasQueryStatus: '进行中'
      });
      
      let retryCount = 0;
      const maxRetries = 30;
      const initialDelay = 200;
      const baseRetryDelay = 150;
      
      const getRetryDelay = (count: number) => {
        const base = initialDelay + baseRetryDelay * Math.min(10, count);
        return base * (0.8 + Math.random() * 0.4);
      };

      const queryCanvas = () => {
        if (!this.data.canvasReady || !this.data.cameraActive) {
          console.log(`第${retryCount+1}次查询被跳过，canvasReady: ${this.data.canvasReady}, cameraActive: ${this.data.cameraActive}`);
          
          if (retryCount < maxRetries) {
            retryCount++;
            const delay = getRetryDelay(retryCount);
            setTimeout(queryCanvas, delay);
          } else {
            console.error('多次尝试后仍找不到AR canvas元素（canvas未准备好）');
            this.setData({ 
              canvasQueryInProgress: false,
              canvasQueryStatus: 'canvas未准备好'
            });
            reject(new Error('canvas未准备好或相机未激活'));
          }
          return;
        }
        
        const query = wx.createSelectorQuery().in(this);
        query.select('#arCanvas').node().exec((res: any) => {
          console.log(`第${retryCount+1}次查询canvas，结果:`, res);
          
          // 增强canvas元素存在性检查
          if (!res || res.length === 0 || !res[0] || !res[0].node) {
            console.error('未获取到有效的canvas元素', res);
            
            if (retryCount < maxRetries) {
              retryCount++;
              const delay = getRetryDelay(retryCount);
              setTimeout(queryCanvas, delay);
            } else {
              const errorMsg = '多次尝试后仍找不到AR canvas元素，请确保页面中存在id为"arCanvas"的canvas元素';
              console.error(errorMsg);
              this.setData({ 
                canvasQueryInProgress: false,
                canvasQueryStatus: '失败',
                errorMsg: errorMsg // 显示错误信息给用户
              });
              reject(new Error(errorMsg));
            }
            return; // 退出当前函数，避免继续执行
          }
          
          // 确认获取到有效的canvas元素
          const canvas = res[0].node;
          if (!canvas || typeof canvas.getContext !== 'function') {
            const errorMsg = '获取到的元素不是有效的canvas元素';
            console.error(errorMsg);
            this.setData({ 
              canvasQueryInProgress: false,
              canvasQueryStatus: '失败',
              errorMsg: errorMsg
            });
            reject(new Error(errorMsg));
            return;
          }
          
          // 修复点1：添加额外的安全检查，确保canvas存在且可设置属性
          if (!canvas || typeof canvas !== 'object' || canvas === null) {
            const errorMsg = '获取到的canvas元素无效，无法设置属性';
            console.error(errorMsg);
            this.setData({ 
              canvasQueryInProgress: false,
              canvasQueryStatus: '失败',
              errorMsg: errorMsg
            });
            reject(new Error(errorMsg));
            return;
          }
          
          try {
            // 修复点2：将canvas属性设置代码包裹在try-catch中，防止意外错误
            // 设置canvas的实际尺寸和显示尺寸
            const systemInfo = wx.getSystemInfoSync();
            const dpr = systemInfo.pixelRatio;
            const width = systemInfo.windowWidth * 0.9; // 使用屏幕宽度的90%
            const height = systemInfo.windowHeight * 0.6; // 使用屏幕高度的60%
            
            // 检查canvas是否有width和height属性
            if (typeof canvas.width === 'undefined' || typeof canvas.height === 'undefined') {
              throw new Error('canvas元素不支持width和height属性');
            }
            
            canvas.width = width * dpr;
            canvas.height = height * dpr;
            
            // 处理样式设置，部分环境可能不支持直接设置style
            if (canvas.style) {
              canvas.style.width = `${width}px`;
              canvas.style.height = `${height}px`;
            } else {
              console.warn('canvas元素不支持style属性，可能影响显示效果');
            }
          } catch (error: any) {
            const errorMsg = `设置canvas属性失败: ${error.message}`;
            console.error(errorMsg);
            this.setData({ 
              canvasQueryInProgress: false,
              canvasQueryStatus: '失败',
              errorMsg: errorMsg
            });
            reject(new Error(errorMsg));
            return;
          }
          
          const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
          
          if (gl) {
            // 配置WebGL上下文参数
            gl.enable(gl.DEPTH_TEST);
            gl.enable(gl.CULL_FACE);
            gl.clearColor(0, 0, 0, 0); // 透明背景
            
            this.setData({ 
              canvas, 
              gl,
              canvasQueryInProgress: false,
              canvasQueryStatus: '成功',
              errorMsg: '' // 清除错误信息
            });
            this.modelLoader = new ModelLoader(canvas, gl);
            this.setData({ modelLoaderReady: true }); // 标记ModelLoader已准备就绪
            resolve();
          } else {
            console.error('WebGL初始化失败');
            this.setData({ 
              canvasQueryInProgress: false,
              canvasQueryStatus: 'WebGL初始化失败',
              errorMsg: 'WebGL初始化失败，无法使用AR功能'
            });
            reject(new Error('WebGL初始化失败'));
          }
        });
      };

      setTimeout(queryCanvas, initialDelay);
    });
  },

  // 检查建筑类型并加载AR内容
  async checkBuildingTypeAndLoadAR(buildingType: string) {
    this.setData({ loading: true, errorMsg: '' });
    
    try {
      if (typeof buildingType !== 'string' || buildingType.trim() === '') {
        this.setData({
          errorMsg: '建筑类型无效，请重新识别',
          loading: false
        });
        return;
      }
      
      // 检查token
      const token = wx.getStorageSync('token');
      if (!token) {
        this.setData({
          errorMsg: '请先登录后再使用AR功能',
          loading: false
        });
        setTimeout(() => {
          wx.navigateTo({ url: '/pages/login/login' });
        }, 1500);
        return;
      }
      
      // 调用后端API
      const res = await sdk.request({
        url: '/api/ar/getMarker',
        method: 'POST',
        header: { 'Authorization': `Bearer ${token}` },
        data: { building_type: buildingType },
        timeout: 10000
      });
      
      // 处理响应
      if (res.code === 0 && res.data) {
        if (!res.data.model_url) {
          this.setData({
            errorMsg: '未找到3D模型资源',
            loading: false
          });
          return;
        }
        
        // 【新增】验证模型URL有效性
        if (!this.isValidModelUrl(res.data.model_url)) {
          this.setData({
            errorMsg: '模型URL无效，必须是GLB或GLTF格式',
            loading: false
          });
          return;
        }
        
        // 更新数据
        this.setData({
          arMarker: {
            id: res.data.id,
            name: res.data.name,
            desc: res.data.description,
            modelUrl: res.data.model_url,
            audioUrls: res.data.audio_urls
          },
          buildingInfo: {
            ...this.data.buildingInfo,
            description: res.data.description || this.data.buildingInfo.description,
            audioUrl: res.data.audio_urls?.mandarin || '',
            dialectAudioUrl: res.data.audio_urls?.hakka || ''
          },
          loading: false,
          isARReady: true,
          canvasReady: true
        });
        
        // 获取模型后立即尝试加载和显示
        this.downloadAndShowModel();
      } else {
        this.setData({
          errorMsg: res.msg || `获取"${this.data.buildingName}"的AR信息失败`,
          loading: false
        });
      }
    } catch (error: any) {
      console.error('加载AR内容失败:', error);
      let errorMsg = `加载"${this.data.buildingName}"的AR内容失败，请重试`;
      
      if (error.errMsg && error.errMsg.includes('timeout')) {
        errorMsg = '网络超时，请检查网络连接后重试';
      } else if (error.errMsg) {
        errorMsg += `: ${error.errMsg}`;
      }
      
      this.setData({
        errorMsg,
        loading: false
      });
    }
  },

  // 【新增】验证模型URL是否有效
  isValidModelUrl(url: string): boolean {
    // 检查URL是否为有效字符串
    if (typeof url !== 'string' || url.trim() === '') return false;
    
    // 检查URL是否以GLB或GLTF扩展名结尾
    const ext = url.split('.').pop()?.toLowerCase();
    return ['glb', 'gltf'].includes(ext || '');
  },

  mapBuildingNameToType(buildingName: string): string {
    const name = buildingName.toLowerCase();
    if (name.includes('圆形土楼') || name.includes('圆楼')) return 'round_tulou';
    if (name.includes('方形土楼') || name.includes('方楼')) return 'square_tulou';
    if (name.includes('围龙屋')) return 'weilong_house';
    if (name.includes('四角楼')) return 'four_corner_house';
    return 'unknown';
  },

  setAudioVersion(e: any) {
    const version = e.currentTarget.dataset.version;
    const isPlaying = this.data.isPlaying;
    
    this.setData({ audioVersion: version });
    
    if (isPlaying) {
      this.toggleAudio();
      setTimeout(() => this.toggleAudio(), 100);
    }
  },

  toggleAudio() {
    const { isPlaying, audioContext, buildingInfo, audioVersion } = this.data;
    const audioUrl = audioVersion === 'mandarin' 
      ? buildingInfo.audioUrl 
      : buildingInfo.dialectAudioUrl;
    
    if (!audioUrl) {
      wx.showToast({
        title: audioVersion === 'mandarin' ? '暂无普通话解说' : '暂无客家话解说',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.audioContext) {
      this.setData({
        audioContext: wx.createInnerAudioContext()
      });
    }
    
    const audioCtx = this.data.audioContext;
    
    if (isPlaying) {
      audioCtx.pause();
    } else {
      audioCtx.src = audioUrl;
      audioCtx.play();
    }
    
    this.setData({
      isPlaying: !isPlaying
    });
  },

  // 打开相机
  openCamera(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.checkCanvasElementExists().then(exists => {
        if (!exists) {
          const errorMsg = '页面中未定义#arCanvas元素，无法初始化AR功能';
          console.error(errorMsg);
          wx.showToast({ title: errorMsg, icon: 'none', duration: 3000 });
          reject(new Error(errorMsg));
          return;
        }
        
        if (this.data.cameraActive) {
          this.closeCamera();
        }
        
        this.setData({
          canvasReady: true,
          cameraActive: true,
          modelVisible: true
        }, () => {
          console.log('设置cameraActive为true，等待DOM渲染');
          
          // 修复点3：增加等待DOM更新的次数，确保canvas元素已渲染
          let domUpdateCount = 0;
          const maxDomUpdates = 5;
          
          const checkDomUpdate = () => {
            if (domUpdateCount >= maxDomUpdates) {
              console.warn('达到最大DOM更新等待次数');
              reject(new Error('等待DOM更新超时'));
              return;
            }
            
            wx.nextTick(() => {
              const query = wx.createSelectorQuery().in(this);
              query.select('#arCanvas').fields({ node: true, size: true }).exec((res) => {
                console.log('查询canvas结果:', res);
                
                if (res && res[0] && res[0].node) {
                  this.initCanvasAndGL()
                    .then(resolve)
                    .catch(reject);
                } else {
                  console.warn(`第${domUpdateCount+1}次查询未找到canvas元素，继续等待`);
                  domUpdateCount++;
                  checkDomUpdate();
                }
              });
            });
          };
          
          checkDomUpdate();
        });
      });
    });
  },
  
  // 检查canvas元素是否在页面中定义
  checkCanvasElementExists(): Promise<boolean> {
    return new Promise((resolve) => {
      let attempts = 0;
      const maxAttempts = 5;
      const check = () => {
        const query = wx.createSelectorQuery().in(this);
        query.select('#arCanvas').boundingClientRect().exec((rectRes) => {
          const exists = rectRes && rectRes.length > 0 && rectRes[0] !== null;
          console.log(`第${attempts+1}次检查canvas元素是否存在:`, exists);
          
          if (exists || attempts >= maxAttempts) {
            resolve(exists);
          } else {
            attempts++;
            setTimeout(check, 200);
          }
        });
      };
      
      check();
    });
  },
  
  // 关闭相机
  closeCamera() {
    this.setData({
      cameraActive: false,
      modelVisible: false,
      modelLoaderReady: false // 重置ModelLoader状态
    });
    
    if (this.modelLoader) {
      this.modelLoader.stopRendering();
      this.modelLoader = null;
    }
    
    this.setData({
      canvas: null,
      gl: null
    });
  },

  // 切换前后摄像头
  switchCamera() {
    this.setData({
      cameraPosition: this.data.cameraPosition === 'back' ? 'front' : 'back'
    });
  },

  // 放大模型
  zoomIn() {
    // 修复：增加反馈提示，确认按钮点击有效
    wx.showToast({
      title: '放大',
      icon: 'none',
      duration: 100
    });
    
    const newScale = Math.min(2.0, this.data.modelScale + 0.1);
    this.setData({
      modelScale: newScale
    });
    
    // 修复：确保modelLoader已初始化
    if (this.modelLoader && this.data.modelLoaderReady) {
      this.modelLoader.setScale(newScale);
    } else {
      console.warn('modelLoader未初始化，无法设置缩放');
      // 尝试重新初始化
      if (this.data.cameraActive) {
        this.downloadAndShowModel();
      }
    }
  },

  // 缩小模型
  zoomOut() {
    // 修复：增加反馈提示，确认按钮点击有效
    wx.showToast({
      title: '缩小',
      icon: 'none',
      duration: 100
    });
    
    const newScale = Math.max(0.5, this.data.modelScale - 0.1);
    this.setData({
      modelScale: newScale
    });
    
    // 修复：确保modelLoader已初始化
    if (this.modelLoader && this.data.modelLoaderReady) {
      this.modelLoader.setScale(newScale);
    } else {
      console.warn('modelLoader未初始化，无法设置缩放');
      // 尝试重新初始化
      if (this.data.cameraActive) {
        this.downloadAndShowModel();
      }
    }
  },

  // 旋转模型
  rotateModel() {
    // 修复：增加反馈提示，确认按钮点击有效
    wx.showToast({
      title: '旋转',
      icon: 'none',
      duration: 100
    });
    
    const newRotation = (this.data.modelRotation + 45) % 360;
    this.setData({
      modelRotation: newRotation
    });
    
    // 修复：确保modelLoader已初始化
    if (this.modelLoader && this.data.modelLoaderReady) {
      this.modelLoader.setRotation(newRotation);
      // 修复：旋转时暂停自动旋转，提升用户体验
      this.modelLoader.toggleAutoRotate(false);
      
      // 5秒后恢复自动旋转
      setTimeout(() => {
        if (this.modelLoader) {
          this.modelLoader.toggleAutoRotate(true);
        }
      }, 5000);
    } else {
      console.warn('modelLoader未初始化，无法设置旋转');
      // 尝试重新初始化
      if (this.data.cameraActive) {
        this.downloadAndShowModel();
      }
    }
  },

  // 下载并显示模型
  async downloadAndShowModel() {
    const { arMarker } = this.data;
    if (!arMarker || !arMarker.modelUrl) {
      wx.showToast({ title: '模型地址无效', icon: 'none' });
      return;
    }

    this.setData({ loading: true });

    try {
      const canvasExists = await this.checkCanvasElementExists();
      if (!canvasExists) {
        throw new Error('页面中未定义#arCanvas元素，无法加载模型');
      }
      
      await this.openCamera();
      
      if (!this.modelLoader) {
        throw new Error('ModelLoader未初始化');
      }
      
      console.log('开始加载模型:', arMarker.modelUrl);
      await this.modelLoader.loadAndRender(
        arMarker.modelUrl,
        this.data.modelScale,
        this.data.modelRotation
      );
      
      this.setData({ loading: false });
    } catch (error) {
      console.error('模型加载失败:', error);
      wx.showToast({ 
        title: error.message || '模型加载失败', 
        icon: 'none',
        duration: 3000
      });
      this.setData({ loading: false });
    }
  },

  toggleFullscreen() {
    this.setData({ fullscreen: !this.data.fullscreen });
    
    if (this.data.fullscreen) {
      wx.setNavigationBarTitle({ title: '' });
      if (typeof wx.hideTabBar === 'function') {
        wx.hideTabBar({ animation: false });
      }
    } else {
      wx.setNavigationBarTitle({ title: 'AR文化解说' });
      if (typeof wx.showTabBar === 'function') {
        wx.showTabBar({ animation: false });
      }
    }
  },

  onRetry() {
    const { buildingType } = this.data;
    if (buildingType) {
      this.checkBuildingTypeAndLoadAR(buildingType);
    }
  },

  navigateBack() {
    if (this.data.cameraActive) {
      this.closeCamera();
    } else {
      wx.navigateBack();
    }
  },

  onUnload() {
    if (this.data.audioContext) {
      this.data.audioContext.stop();
    }
    
    if (this.data.cameraActive) {
      this.closeCamera();
    }
    
    if (this.modelLoader) {
      this.modelLoader.stopRendering();
    }
  }
});